package com.hjj.services;

import com.hjj.beans.Stu;
import com.hjj.dao.StuDao;
import com.hjj.dao.StuDaoImp;
import com.hjj.exception.MyRoundException;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Map;

public class StuServicesImp implements StuServices{
    // 关联数据层
    private StuDao stuDao = new StuDaoImp();


    @Override
    public ArrayList<Stu> getAll() throws SQLException {
        return stuDao.getAll();
    }

    @Override
    public Stu get(int id) throws SQLException {
        return stuDao.get(id);
    }

    @Override
    public String callRoll(int id) throws SQLException, MyRoundException {
        ArrayList<Stu> all = stuDao.getAll();

        if (id < 1) throw new MyRoundException("点名人数不能低于1");

        if (id > all.size()) throw new MyRoundException("点名人数不能超过学生人数");

        // 创建HashSet集合用于存储学生数据的下标
        HashSet<Integer> indexs = new HashSet<>();

        // 使用while循环加随机数生成不重复的index
        while (indexs.size() != id){
            indexs.add((int)(Math.random()*all.size()));
        }

        // 创建StringBuffer用于存储点名名单
        StringBuffer stringBuffer = new StringBuffer();

        // 循环下标集合拿取姓名
        for (Integer index : indexs) {
            stringBuffer.append(all.get(index).getName() + "\n");
        }

        return stringBuffer.toString();
    }

    @Override
    public boolean add(Stu stu) throws SQLException, MyRoundException {
        int length = stu.getName().length();
        if (length < 2 || length > 10) throw new MyRoundException("姓名长度只能在2~10之间");

        int age = stu.getAge();
        if (age < 14 || age > 30) throw new MyRoundException("年龄范围只能在14~30之间");

        float score = stu.getScore();
        if (score < 0 || score > 100) throw new MyRoundException("成绩只能在0~100之间");

        int add = stuDao.add(stu);
        return add > 0 ? true : false;
    }

    @Override
    public boolean edit(Stu stu) throws SQLException, MyRoundException {
        int length = stu.getName().length();
        if (length < 2 || length > 10) throw new MyRoundException("姓名长度只能在2~10之间");

        int age = stu.getAge();
        if (age < 14 || age > 30) throw new MyRoundException("年龄范围只能在14~30之间");

        float score = stu.getScore();
        if (score < 0 || score > 100) throw new MyRoundException("成绩只能在0~100之间");

        int edit = stuDao.edit(stu);
        return edit > 0 ? true : false;
    }

    @Override
    public boolean del(int id) throws SQLException {
        return stuDao.del(id) > 0 ? true : false;
    }
}
